﻿using HuiLian.Common.Extensions;
using HuiLian.BigData.Hdl.Helper;
using HuiLian.BigData.Hdl.HttpModel;
using HuiLian.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HuiLian.BigData.Hdl.Model;
using AutoMapper;
using HuiLian.BigData.Hdl.Comparer;
using Newtonsoft.Json;
using Org.BouncyCastle.Utilities.Collections;

namespace HuiLian.BigData.Hdl
{
    public partial class MainForm : Form
    {
        private readonly IMapper _mapper;
        private readonly IFreeSql _fsql;
        private readonly HttpHelper _httpHelper;

        public MainForm(IMapper mapper, IFreeSql fsql, HttpHelper httpHelper)
        {
            _mapper = mapper;
            _fsql = fsql;
            _httpHelper = httpHelper;

            InitializeComponent();
        }


        private async void BtnRealmsZzssProtocol_Click(object sender, EventArgs e)
        {
            try
            {
                var result = await _httpHelper.RealmsZzssProtocolTokenResponseAsync();
                GlobalVariable.RealmsZzssProtocolToken = result.access_token;
                MessageBox.Show($"大数据平台登录成功,{result.access_token}");

                //GlobalVariable.RealmsZzssProtocolToken = @"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJzNW10RC1mdzJUSjh0bE9YY3JMZ3U0ZExZTHZWdVBCM0VkQmdpek80WGxZIn0.eyJleHAiOjE3MzI3MDI0MTQsImlhdCI6MTczMjY5ODgxNCwianRpIjoiODRmNjZiNzktY2I4Ny00OGNkLWJmY2UtNDY5MDQ3OTRkMjg3IiwiaXNzIjoiaHR0cDovLzEwLjEuOC44MDo4MDgxL3JlYWxtcy96enNzIiwiYXVkIjoiYWNjb3VudCIsInN1YiI6IjQyMGJjZTNiLTcyYTEtNDUzZC05MjY5LTNhZWRmZWM4YTM0ZSIsInR5cCI6IkJlYXJlciIsImF6cCI6Imd3c2IiLCJhY3IiOiIxIiwiYWxsb3dlZC1vcmlnaW5zIjpbImh0dHA6Ly8xOTIuMTY4LjI0OS42NiJdLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsiZGVmYXVsdC1yb2xlcy16enNzIiwib2ZmbGluZV9hY2Nlc3MiLCJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfSwiZ3dzYiI6eyJyb2xlcyI6WyJ1bWFfcHJvdGVjdGlvbiJdfX0sInNjb3BlIjoicHJvZmlsZSBlbWFpbCBvcGVuaWQiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImNsaWVudEhvc3QiOiIxMC4xLjguMTE4IiwicHJlZmVycmVkX3VzZXJuYW1lIjoic2VydmljZS1hY2NvdW50LWd3c2IiLCJjbGllbnRBZGRyZXNzIjoiMTAuMS44LjExOCIsImNsaWVudF9pZCI6Imd3c2IifQ.SSCLvESDfz6gzDBKC-pwoYPjezfoGHx7G33Jwmh81M8Whs4GA7OPPVyI7z_VdraoYcFTLOqc_YSYtwMzzeDrPo_ESlXaQoOcN2ZVdiEjZ0KRFAlNb01dHiAgGB5GuwXRvU3FBP5fT8fOienV0TCD-9veo72_PcbU6VFVNDsgW7wN41wIzYDO4BV0puVPt8UZrLwDwrjLdIzk5pAk7UnWgfPb8rksXatZW8E-xsr11exC08p46FjWn6YD6sojLPwI80lTkWydKtpNvr8ZI9ZEVL7uSmdRGPhv3zrZSnP9XTvjXoWJfSjAyZy9eB7ATO5r4LGqZiIWn4a-hHf7CAfm4g";
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误：" + ex.Message);
            }
        }

        private async void BtnHdlOauthAccess_Click(object sender, EventArgs e)
        {
            //大数据登录
            try
            {
                string client_id = "g2xmb";
                string client_secret = "ff914307";
                var access = await _httpHelper.HdlOauthAccessResponseAsync(client_id, client_secret);
                GlobalVariable.HdlOauthAccessToken = access.access_token;
                MessageBox.Show($"获取Token成功,{Newtonsoft.Json.JsonConvert.SerializeObject(access)}");
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误：" + ex.Message);
            }
        }

        private async void BtnStationInfo_Click(object sender, EventArgs e)
        {
            //List<HdlScadaStationInfoResponseData> dataList = InitHdlScadaStationInfoTestDataList();
            //await HdlScadaStationInfoAddOrUpdate(dataList);

            HdlScadaStationInfoRequest request = new HdlScadaStationInfoRequest();
            var stationInfo = await _httpHelper.HdlScadaStationInfoResponseAsync(request);
            if (stationInfo != null && stationInfo.Code == 0)
            {
                MessageBox.Show($"站点信息数量{stationInfo.Response.Count}");
                dgvData.DataSource = stationInfo.Response;

                //await HdlScadaStationInfoAddOrUpdate(stationInfo.Response);
            }
            else
            {
                MessageBox.Show("站点信息为null");
            }
        }

        private List<HdlScadaStationInfoResponseData> InitHdlScadaStationInfoTestDataList()
        {
            List<HdlScadaStationInfoResponseData> dataList = new List<HdlScadaStationInfoResponseData>()
            {
                new HdlScadaStationInfoResponseData
                {
                    id = "1",
                    cate = "pipe_1",
                    dma = "dma_1",
                    code = "1",
                    name = "1_name",
                    address = "1_address"
                },
                new HdlScadaStationInfoResponseData
                {
                    id = "2",
                    cate = "pipe_2",
                    dma = "dma_2",
                    code = "2",
                    name = "2_name",
                    address = "2_address"
                },
                new HdlScadaStationInfoResponseData
                {
                    id = "3",
                    code = "3",
                    name = "3_name",
                    address = "3_address"
                },
                new HdlScadaStationInfoResponseData
                {
                    id = "4",
                    code = "4",
                    name = "4_name",
                    address = "4_address"
                },
                new HdlScadaStationInfoResponseData
                {
                    id = "5",
                    code = "5",
                    name = "5_name",
                    address = "5_address"
                }
            };
            return dataList;
        }

        private async Task HdlScadaStationInfoAddOrUpdate(List<HdlScadaStationInfoResponseData> data)
        {
            //添加或更新到数据库
            var list = await _fsql.Select<HdlScadaStationInfoEntity>().ToListAsync();
            List<string> ids = list.Select(p => p.id).ToList();
            var addList = data.Where(p => !ids.Contains(p.id)).ToList();
            var entity = _mapper.Map<List<HdlScadaStationInfoEntity>>(addList);
            if (entity.Count > 0)
            {
                _fsql.Insert(entity).ExecuteAffrows();
            }
            //更新
            var updateList = data.Where(p => ids.Contains(p.id)).ToList();
            var updateEntityList = list.Where(p => ids.Contains(p.id)).ToList();
            if (updateEntityList != null && updateEntityList.Count > 0)
            {
                _mapper.Map(updateList, updateEntityList);
                _fsql.Update<HdlScadaStationInfoEntity>().SetSource(updateEntityList).ExecuteAffrows();
            }
        }

        private async void BtnSensorInfo_Click(object sender, EventArgs e)
        {
            //List<HdlScadaSensorInfoResponseData> dataList = InitHdlScadaSensorInfoTestDataList();
            //await HdlScadaSensorInfoAddOrUpdate(dataList);

            HdlScadaSensorInfoRequest request = new HdlScadaSensorInfoRequest();
            var sensorInfo = await _httpHelper.HdlScadaSensorInfoAsync(request);
            if (sensorInfo != null)
            {
                MessageBox.Show($"传感器信息数量{sensorInfo.Response.Count}");
                dgvData.DataSource = sensorInfo.Response;

                //await HdlScadaSensorInfoAddOrUpdate(sensorInfo.Response);
            }
            else
            {
                MessageBox.Show("传感器信息为null");
            }
        }

        /// <summary>
        /// 初始化测试数据
        /// </summary>
        /// <returns></returns>
        private List<HdlScadaSensorInfoResponseData> InitHdlScadaSensorInfoTestDataList()
        {
            List<HdlScadaSensorInfoResponseData> dataList = new List<HdlScadaSensorInfoResponseData>()
            {
                new HdlScadaSensorInfoResponseData
                {
                    cate = "pipe",
                    group_code = "group",
                    sensor_code = "1",
                    sensor_name = "1_name",
                    station_code = "1"
                },
                new HdlScadaSensorInfoResponseData
                {
                    cate = "pipe",
                    group_code = "group",
                    sensor_code = "2",
                    sensor_name = "2_name",
                    station_code = "2"
                },
                new HdlScadaSensorInfoResponseData
                {
                    cate = "pipe",
                    group_code = "group",
                    sensor_code = "3",
                    sensor_name = "3_name",
                    station_code = "3"
                },
                new HdlScadaSensorInfoResponseData
                {
                    cate = "pipe",
                    group_code = "group",
                    sensor_code = "4",
                    sensor_name = "4_name",
                    station_code = "4"
                },
                new HdlScadaSensorInfoResponseData
                {
                    cate = "pipe",
                    group_code = "group",
                    sensor_code = "5",
                    sensor_name = "5_name",
                    station_code = "5"
                },
            };
            return dataList;
        }

        private async Task HdlScadaSensorInfoAddOrUpdate(List<HdlScadaSensorInfoResponseData> data)
        {
            //添加或更新到数据库
            var list = await _fsql.Select<HdlScadaSensorInfoEntity>().ToListAsync();
            List<string> codes = list.Select(p => p.sensor_code).ToList();
            var addList = data.Where(p => !codes.Contains(p.sensor_code)).ToList();
            var entity = _mapper.Map<List<HdlScadaSensorInfoEntity>>(addList);
            if (entity.Count > 0)
            {
                _fsql.Insert(entity).ExecuteAffrows();
            }
            //更新
            //var updateList = data.Where(p => codes.Contains(p.sensor_code)).ToList();
            //var updateEntityList = list.Where(p => codes.Contains(p.sensor_code)).ToList();
            //if (updateEntityList != null && updateEntityList.Count > 0)
            //{
            //    _mapper.Map(updateList, updateEntityList);
            //    _fsql.Update<HdlScadaSensorInfoEntity>().SetSource(updateEntityList).ExecuteAffrows();
            //}

            //只更新变化的属性
            var updateList = data.Where(p => codes.Contains(p.sensor_code)).ToList();
            var sensorInfoRepo = _fsql.GetRepository<HdlScadaSensorInfoEntity>();
            var updateEntityList = sensorInfoRepo.Where(p => codes.Contains(p.sensor_code)).ToList();
            if (updateEntityList != null && updateEntityList.Count > 0)
            {
                _mapper.Map(updateList, updateEntityList);
                await sensorInfoRepo.UpdateAsync(updateEntityList);
            }
        }

        private async void BtnSensorRealTime_Click(object sender, EventArgs e)
        {
            //List<HdlScadaSensorRealTimeResponseData> dataList = InitHdlScadaSensorRealTimeTestDataList();
            //await HdlScadaSensorRealTimeAddOrUpdate(dataList);

            HdlScadaSensorRealTimeRequest request = new HdlScadaSensorRealTimeRequest();
            var sensorRealTime = await _httpHelper.HdlScadaSensorRealTimeAsync(request);
            if (sensorRealTime != null)
            {
                MessageBox.Show($"实时数据数量{sensorRealTime.Response.Count}");
                dgvData.DataSource = sensorRealTime.Response;

                //await HdlScadaSensorRealTimeAddOrUpdate(sensorRealTime.Response);
            }
            else
            {
                MessageBox.Show("实时数据为null");
            }
        }

        /// <summary>
        /// 初始化测试数据
        /// </summary>
        /// <returns></returns>
        private List<HdlScadaSensorRealTimeResponseData> InitHdlScadaSensorRealTimeTestDataList()
        {
            List<HdlScadaSensorRealTimeResponseData> dataList = new List<HdlScadaSensorRealTimeResponseData>()
            {
                new HdlScadaSensorRealTimeResponseData
                {
                    code = "1",
                    pre_time = 1731236576001,
                    pre_val = 1.1,
                    station = "1",
                    time = 1731554391001,
                    value = 1.11
                },
                new HdlScadaSensorRealTimeResponseData
                {
                    code = "2",
                    pre_time = 1731236576002,
                    pre_val = 1.2,
                    station = "2",
                    time = 1731554391002,
                    value = 1.21
                },
                new HdlScadaSensorRealTimeResponseData
                {
                    code = "3",
                    pre_time = 1731236576003,
                    pre_val = 1.3,
                    station = "3",
                    time = 1731554391000,
                    value = 1.31
                },
                new HdlScadaSensorRealTimeResponseData
                {
                    code = "4",
                    pre_time = 1731236576004,
                    pre_val = 1.4,
                    station = "4",
                    time = 1731554391000,
                    value = 1.41
                },
                new HdlScadaSensorRealTimeResponseData
                {
                    code = "5",
                    pre_time = 1731236576005,
                    pre_val = 1.5,
                    station = "5",
                    time = 1731554391000,
                    value = 1.51
                },
            };
            return dataList;
        }

        private async Task HdlScadaSensorRealTimeAddOrUpdate(List<HdlScadaSensorRealTimeResponseData> data)
        {
            //添加或更新到数据库
            var list = await _fsql.Select<HdlScadaSensorRealTimeEntity>().ToListAsync();
            List<string> codes = list.Select(p => p.code).ToList();
            var addList = data.Where(p => !codes.Contains(p.code)).ToList();
            var entity = _mapper.Map<List<HdlScadaSensorRealTimeEntity>>(addList);
            if (entity.Count > 0)
            {
                _fsql.Insert(entity).ExecuteAffrows();
            }
            //更新
            //var updateList = data.Where(p => codes.Contains(p.sensor_code)).ToList();
            //var updateEntityList = list.Where(p => codes.Contains(p.sensor_code)).ToList();
            //if (updateEntityList != null && updateEntityList.Count > 0)
            //{
            //    _mapper.Map(updateList, updateEntityList);
            //    _fsql.Update<HdlScadaSensorInfoEntity>().SetSource(updateEntityList).ExecuteAffrows();
            //}

            //只更新变化的属性
            var updateList = data.Where(p => codes.Contains(p.code)).ToList();
            var sensorRealTimeRepo = _fsql.GetRepository<HdlScadaSensorRealTimeEntity>();
            var updateEntityList = sensorRealTimeRepo.Where(p => codes.Contains(p.code)).ToList();
            if (updateEntityList != null && updateEntityList.Count > 0)
            {
                _mapper.Map(updateList, updateEntityList);
                await sensorRealTimeRepo.UpdateAsync(updateEntityList);
            }
        }

        private async void BtnSensorHistory_Click(object sender, EventArgs e)
        {
            //List<HdlScadaSensorHistoryResponseData> dataList = InitHdlScadaSensorHistoryTestDataList();
            //await HdlScadaSensorHistoryAddOrUpdate(dataList);

            HdlScadaSensorHistoryRequest request = new HdlScadaSensorHistoryRequest();
            DateTime dt = DateTime.Now;
            DateTime beginDt = Convert.ToDateTime("2024-10-01 00:00:00");
            DateTime endDt = Convert.ToDateTime("2024-12-01 00:00:00");

            //从文件里读取传感器信息
            HdlScadaSensorInfoResponse sensorInfo = ReadSensorInfoByFile();
            if (sensorInfo == null || sensorInfo.Response == null)
            {
                MessageBox.Show("获取传感器数据为null");
                return;
            }

            HdlScadaSensorHistoryResponse sensorHistory = null;
            int refreshToken = 10;
            for (int i = 61; i < sensorInfo.Response.Count; i++)
            {
                #region 定期刷新token

                if (i % refreshToken == 0)
                {
                    //刷新token
                    var result = await _httpHelper.RealmsZzssProtocolTokenResponseAsync();
                    if (result.access_token == null)
                    {
                        MessageBox.Show("获取大数据对接的token为null");
                        return;
                    }
                    GlobalVariable.RealmsZzssProtocolToken = result.access_token;

                    System.Threading.Thread.Sleep(200);

                    string client_id = "g2xmb";
                    string client_secret = "ff914307";
                    var access = await _httpHelper.HdlOauthAccessResponseAsync(client_id, client_secret);
                    if (access.access_token == null)
                    {
                        MessageBox.Show("获取的token为null");
                        return;
                    }
                    GlobalVariable.HdlOauthAccessToken = access.access_token;
                }

                #endregion

                HdlScadaSensorInfoResponseData sensor = sensorInfo.Response[i];
                if (sensor == null) continue;
                //if(sensor.sensor_code == "6552dae726ab7bca24432450")
                //{

                //}
                //else
                //{
                //    continue;
                //}

                for (DateTime sdt = beginDt; sdt < endDt; sdt = sdt.AddDays(1))
                {
                    var edt = sdt.AddDays(1);
                    request.begin = sdt.ToTimestamp();
                    request.end = edt.ToTimestamp();
                    request.codes = new List<string>() { sensor.sensor_code };

                    sensorHistory = await _httpHelper.HdlScadaSensorHistoryAsync(request);
                    if(sensorHistory == null)
                    {
                        MessageBox.Show($"当前的传感器编号是{sensor.sensor_code}");
                        return;
                    }
                    System.Threading.Thread.Sleep(200);
                   
                }
            }
            MessageBox.Show("历史数据获取完成");
            
            if (sensorHistory != null && sensorHistory.Code == 0)
            {
                MessageBox.Show($"历史数据数量{sensorHistory.Response.Count}");
                dgvData.DataSource = sensorHistory.Response;

                //await HdlScadaSensorHistoryAddOrUpdate(sensorHistory.Response);
            }
            else
            {
                MessageBox.Show("历史数据为null");
            }
        }

        /// <summary>
        /// 初始化测试数据
        /// </summary>
        /// <returns></returns>
        private List<HdlScadaSensorHistoryResponseData> InitHdlScadaSensorHistoryTestDataList()
        {
            List<HdlScadaSensorHistoryResponseData> dataList = new List<HdlScadaSensorHistoryResponseData>()
            {
                new HdlScadaSensorHistoryResponseData
                {
                    code = "1",
                    time = 1731554391021,
                    value = 1.11
                },
                new HdlScadaSensorHistoryResponseData
                {
                    code = "2",
                    time = 1731554391022,
                    value = 1.21
                },
                new HdlScadaSensorHistoryResponseData
                {
                    code = "3",
                    time = 1731554391000,
                    value = 1.31
                },
                new HdlScadaSensorHistoryResponseData
                {
                    code = "4",
                    time = 1731554391000,
                    value = 1.41
                },
                new HdlScadaSensorHistoryResponseData
                {
                    code = "5",
                    time = 1731554391000,
                    value = 1.51
                },
            };
            return dataList;
        }

        private async Task HdlScadaSensorHistoryAddOrUpdate(List<HdlScadaSensorHistoryResponseData> data)
        {
            //如果有不存在的，就添加到数据库
            var entity = _mapper.Map<List<HdlScadaSensorHistoryEntity>>(data);
            var list = await _fsql.Select<HdlScadaSensorHistoryEntity>().ToListAsync();
            var addList = entity.Except(list, new HdlScadaSensorHistoryComparer());
            if (addList != null && addList.Count() > 0)
            {
                _fsql.Insert(addList).ExecuteAffrows();
            }
            //更新
            //var updateList = data.Where(p => codes.Contains(p.sensor_code)).ToList();
            //var updateEntityList = list.Where(p => codes.Contains(p.sensor_code)).ToList();
            //if (updateEntityList != null && updateEntityList.Count > 0)
            //{
            //    _mapper.Map(updateList, updateEntityList);
            //    _fsql.Update<HdlScadaSensorInfoEntity>().SetSource(updateEntityList).ExecuteAffrows();
            //}

            //只更新变化的属性
            //var updateList = data.Where(p => codes.Contains(p.code)).ToList();
            //var sensorHistoryRepo = _fsql.GetRepository<HdlScadaSensorHistoryEntity>();
            //var updateEntityList = sensorHistoryRepo.Where(p => codes.Contains(p.code)).ToList();
            //if (updateEntityList != null && updateEntityList.Count > 0)
            //{
            //    _mapper.Map(updateList, updateEntityList);
            //    await sensorHistoryRepo.UpdateAsync(updateEntityList);
            //}
        }

        private async void BtnRealmsZzssProtocolUserInfo_Click(object sender, EventArgs e)
        {
            string url = "http://10.1.8.80:8081/realms/zzss/protocol/openid-connect/userinfo";
            List<RequestHeader> requestHeaders = new List<RequestHeader>()
            {
                new RequestHeader
                {
                    Name = "Authorization",
                    Value = $"Bearer {GlobalVariable.RealmsZzssProtocolToken}"
                }
            };
            var result = await _httpHelper.PostAuthAsync<RealmsZzssProtocolUserInfoResponse>(url, new { }, requestHeaders);
            MessageBox.Show(Newtonsoft.Json.JsonConvert.SerializeObject(result));
            if (result == null || string.IsNullOrWhiteSpace(result.preferred_username))
            {
                MessageBox.Show("用户认证失败，用户不存在");
            }
        }

        private async void BtnAlarmHistory_Click(object sender, EventArgs e)
        {
            HdlScadaAlarmHistoryRequest request = new HdlScadaAlarmHistoryRequest();
            //DateTime dt = DateTime.Now;
            //request.stimeBegin = dt.AddHours(-5).ToTimestamp();
            //request.stimeEnd = dt.ToTimestamp();
            DateTime beginDt = Convert.ToDateTime("2024-11-30 00:00:00");
            DateTime endDt = Convert.ToDateTime("2024-12-01 00:00:00");
            HdlScadaAlarmHistoryResponse sensorHistory = null;
            for (DateTime sdt = beginDt; sdt < endDt; sdt = sdt.AddDays(1))
            {
                var edt = sdt.AddDays(1);
                request.stimeBegin = sdt.ToTimestamp();
                request.stimeEnd = edt.ToTimestamp();
                request.index = 0;
                if (sdt == Convert.ToDateTime("2024-11-30 00:00:00")) { request.index = 9; }
                request.size = 50;
                do
                {
                    request.index += 1;

                    //request.codes = new List<string>();
                    //request.codes.Add("ZZ001020210108A60");
                    sensorHistory = await _httpHelper.HdlScadaAlarmHistoryAsync(request);
                    System.Threading.Thread.Sleep(200);
                    //MessageBox.Show($"{request.index}");
                }
                while (sensorHistory != null && sensorHistory.Code == 0 && (request.index * request.size < sensorHistory.Response.total));
            }

            if (sensorHistory != null && sensorHistory.Code == 0)
            {
                MessageBox.Show($"历史报警记录数量{sensorHistory.Response.rows.Count}");
                //dgvData.DataSource = sensorHistory.Response;

                //await HdlScadaAlarmHistoryAddOrUpdate(sensorHistory.Response.rows);
            }
            else
            {
                MessageBox.Show("历史报警记录为null");
            }
        }

        private async Task HdlScadaAlarmHistoryAddOrUpdate(List<HdlScadaAlarmHistoryResponseDataRows> data)
        {
            //如果有不存在的，就添加到数据库
            var entity = _mapper.Map<List<HdlScadaAlarmHistoryEntity>>(data);
            var list = await _fsql.Select<HdlScadaAlarmHistoryEntity>().ToListAsync();
            var addList = entity.Except(list, new HdlScadaAlarmHistoryComparer());
            if (addList != null && addList.Count() > 0)
            {
                _fsql.Insert(addList).ExecuteAffrows();
            }
            if (addList.Count() != 0 && addList.Count() != data.Count)
            {

            }
            //更新
            //var updateList = data.Where(p => codes.Contains(p.sensor_code)).ToList();
            //var updateEntityList = list.Where(p => codes.Contains(p.sensor_code)).ToList();
            //if (updateEntityList != null && updateEntityList.Count > 0)
            //{
            //    _mapper.Map(updateList, updateEntityList);
            //    _fsql.Update<HdlScadaSensorInfoEntity>().SetSource(updateEntityList).ExecuteAffrows();
            //}

            //只更新变化的属性
            //var updateList = data.Where(p => codes.Contains(p.code)).ToList();
            //var sensorHistoryRepo = _fsql.GetRepository<HdlScadaSensorHistoryEntity>();
            //var updateEntityList = sensorHistoryRepo.Where(p => codes.Contains(p.code)).ToList();
            //if (updateEntityList != null && updateEntityList.Count > 0)
            //{
            //    _mapper.Map(updateList, updateEntityList);
            //    await sensorHistoryRepo.UpdateAsync(updateEntityList);
            //}
        }

        /// <summary>
        /// 站点信息入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnSaveStationInfo_Click(object sender, EventArgs e)
        {
            string path = @"E:\项目\自来水健康评价\大数据API对接\和达数据\station  站点\info/_info.json";
            var isExists = System.IO.File.Exists(path);
            if (!isExists)
            {
                MessageBox.Show("文件不存在");
                return;
            }
            var info = System.IO.File.ReadAllText(path);
            if (string.IsNullOrEmpty(info))
            {
                MessageBox.Show("没有内容");
                return;
            }
            HdlScadaStationInfoResponse stationInfo = JsonConvert.DeserializeObject<HdlScadaStationInfoResponse>(info);
            if (stationInfo == null)
            {
                MessageBox.Show("序列化失败");
                return;
            }
            if (stationInfo.Response != null && stationInfo.Response.Count > 0)
            {
                await HdlScadaStationInfoAddOrUpdate(stationInfo.Response);
            }
        }

        private HdlScadaSensorInfoResponse ReadSensorInfoByFile()
        {
            //string path = @"E:\项目\自来水健康评价\大数据API对接\和达数据\sensor  传感器\info/_info.json";
            string path = @"sensor\info\_info.json";
            var isExists = System.IO.File.Exists(path);
            if (!isExists)
            {
                MessageBox.Show("文件不存在");
                return null;
            }
            var info = System.IO.File.ReadAllText(path);
            if (string.IsNullOrEmpty(info))
            {
                MessageBox.Show("没有内容");
                return null;
            }
            HdlScadaSensorInfoResponse sensorInfo = JsonConvert.DeserializeObject<HdlScadaSensorInfoResponse>(info);
            if (sensorInfo == null)
            {
                MessageBox.Show("序列化失败");
                return null;
            }
            return sensorInfo;
        }

        private async void BtnSaveSensorInfo_Click(object sender, EventArgs e)
        {
            HdlScadaSensorInfoResponse sensorInfo = ReadSensorInfoByFile();
            if(sensorInfo == null || sensorInfo.Response == null)
            {
                MessageBox.Show("获取传感器数据为null");
                return;
            }

            if (sensorInfo.Response != null && sensorInfo.Response.Count > 0)
            {
                await HdlScadaSensorInfoAddOrUpdate(sensorInfo.Response);
            }
        }

        private async void BtnSaveAlarmHistory_Click(object sender, EventArgs e)
        {
            string folderPath = @"E:\项目\自来水健康评价\大数据API对接\和达数据\alarm 10月1号到11月30号的数据\alarm\history"; // 替换为你的文件夹路径
            string[] fileNames = Directory.GetFiles(folderPath, "*", SearchOption.AllDirectories);
            foreach (string fileName in fileNames)
            {
                var isExists = System.IO.File.Exists(fileName);
                if (!isExists)
                {
                    MessageBox.Show("文件不存在");
                    return;
                }
                var alarmHistory = System.IO.File.ReadAllText(fileName);
                if (string.IsNullOrEmpty(alarmHistory))
                {
                    MessageBox.Show("没有内容");
                    return;
                }
                HdlScadaAlarmHistoryResponse alarmHistoryResponse = JsonConvert.DeserializeObject<HdlScadaAlarmHistoryResponse>(alarmHistory);
                if (alarmHistoryResponse == null)
                {
                    MessageBox.Show("序列化失败");
                    return;
                }
                if (alarmHistoryResponse.Response != null && alarmHistoryResponse.Response.rows.Count > 0)
                {
                    await HdlScadaAlarmHistoryAddOrUpdate(alarmHistoryResponse.Response.rows);
                }
            }
        }

        private async void BtnSaveSensorRealTime_Click(object sender, EventArgs e)
        {
            string path = @"E:\项目\自来水健康评价\大数据API对接\和达数据\sensor  传感器\realtime/_realtime.json";
            var isExists = System.IO.File.Exists(path);
            if (!isExists)
            {
                MessageBox.Show("文件不存在");
                return;
            }
            var info = System.IO.File.ReadAllText(path);
            if (string.IsNullOrEmpty(info))
            {
                MessageBox.Show("没有内容");
                return;
            }
            HdlScadaSensorRealTimeResponse sensorRealTime = JsonConvert.DeserializeObject<HdlScadaSensorRealTimeResponse>(info);
            if (sensorRealTime == null)
            {
                MessageBox.Show("序列化失败");
                return;
            }
            if (sensorRealTime.Response != null && sensorRealTime.Response.Count > 0)
            {
                await HdlScadaSensorRealTimeAddOrUpdate(sensorRealTime.Response);
            }
        }
    }
}
